"use strict";

const util = require('util');
function merge(vals, operator, chain) {
    let conds = [], data = [];

    vals.forEach(function (val) {
        where(val, function (vals, txt) {
            data.push.apply(data, vals);
            conds.push(txt);
        });
    });
    return chain(data, conds.length == 1 ? conds[0] : '(' + conds.join(operator) + ')');
}

function escape(value) {
    return util.format('"%s"', value);
}

function cond(k, v, chain) {
    k = escape(k);
    let type = typeof v;

    if (Array.isArray(v) && v.length == 0)
        return chain([], "FALSE");
    if (type == "object")
        return chain([], `${k} IS${v === null ? '' : ' NOT'} NULL`);
    if (type == "boolean")
        return chain([], util.format(v ? '%s' : 'NOT(%s)', k));

    //if(type == "number" || type == "string") //what else..
    return chain([v], util.format('%s=?:', k));
}

function where(vals, chain) {
    return chain([], vals);
}

const mask = new RegExp(`(-)?(#)?(?:"([^"]+)"|'([^']+)'|([^\\s,]+))|(\\s*,\\s*)`, 'g');
const explode_search_blob = function(qs) {
    qs = qs.trim();
    let out = [], tmp;
    while((tmp = mask.exec(qs)))
      out.push(tmp);
    return out;
  };

function res(main_field, qs) {
    let out = explode_search_blob(qs);
    let parts = [[]], part = 0;
    out.forEach(function(arg) {
      if(arg[6])
        return parts[++part] = [];

      let value = (arg[3] || arg[4] || arg[5]);
      parts[part].push({ [main_field] : value });
    })
  
    let results;

    merge(parts, ' OR ', function (data, txt) {
        results = { data, txt };
    });
};
